package cn.mxlshy.springcloud.controller;


import cn.mxlshy.springcloud.service.IPaymentService;
import entities.CommonResult;
import entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 马晓亮
 * @since 2020-08-03
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private IPaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        boolean result = paymentService.save(payment);
        if (result) {
            return new CommonResult(200,"插入成功"+serverPort,result);
        }
        return new CommonResult(444,"插入失败",null);
    }
    @GetMapping("/payment/get/{id}")
    public CommonResult  getPayment(@PathVariable Long id) {

        Payment result = paymentService.getById(id);
        if (result != null) {

            return new CommonResult(200, "查询成功"+serverPort, result);
        }
        return new CommonResult(444,"查询失败",null);
    }
    @GetMapping("/payment/discovery")
    public Object discover() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("=====service:->{}",service);
        }
        List<ServiceInstance> instanceInfos =   discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instanceInfo : instanceInfos) {
            log.info("instance->{}",instanceInfo.getServiceId()+"\t"+instanceInfo.getHost()+"\t" + instanceInfo.getUri());
        }
        return this.discoveryClient;
    }


    @GetMapping("/payment/lb")
    public String getPayment() {
        return serverPort;
    }

    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return "hello,this is paymentZipkin server response,How do you do~";
    }
}

